<?php
require_once(__PHY_LIB.'/class/Item.class.php');
require_once(__PHY_LIB.'/func/Transition.func.php');
require_once(__PHY_LIB.'/func/Server.func.php');

class uUser extends Item {
/// definition and constructor ///
    function uUser($id=0, $field="") {
        Query::Query();
        $this->cfgKeyField("id");
        $this->cfgAllField("id,email,nick,pswd,time_added,time_lastlogin,thumb,sign,sign_en,gender,demo,description,description_en,role_artist");
        $this->cfgTable("unit_user");
        if ("" == $field || "*" == $field) {
            $this->cfgField($this->mAllField);
        }
        else {
            $this->cfgField($field);
        }
        if (0 < $id) {
            $this->cfgWhere($this->mKeyField . "=" . $id);
            $this->load();
        }
        else {
            $this->set($this->mKeyField, $id);
        }
    }

    function loadByEmail($sEmail) {
        $this->cfgWhere("email='".addslashes($sEmail)."'");
        $this->load();
    }
    function loadByNick($sNick) {
        $this->cfgWhere("nick='".addslashes($sNick)."'");
        $this->load();
    }

    function pswdEncode($sPswd) {
        return md5('pswd'.$sPswd);
    }

    function invalid() {
        if (!strpos($this->get('email'), '@')) {
            return 'email';
        }

        return false;
    }

    function logout() {
        setcookie('u_type', '', time()-86400, '/', '.'.__ENV_DMN); unset($_COOKIE['u_type']);
        setcookie('u_id',   '', time()-86400, '/', '.'.__ENV_DMN); unset($_COOKIE['u_id']);
        setcookie('u_nick', '', time()-86400, '/', '.'.__ENV_DMN); unset($_COOKIE['u_nick']);
        /// 销毁session ///
        unset($_SESSION['u_id']);
        return true;
    }

    function login($sAcct, $sPswd, $bLong=false) {
        if (!$sAcct || !$sPswd) { return false; }
        $oUser = new uUser();
        $oUser->loadByEmail($sAcct);
        if ($oUser->pswdEncode($sPswd) == $oUser->get('pswd')) {
            /// 设置cookie ///
            $_SESSION['u_id'] = $oUser->getID();
            $nExpire = $bLong ? (time() + 86400*30) : null; // 30天cookie过期
            setcookie('u_type', 'user',              $nExpire, '/', '.'.__ENV_DMN); $_COOKIE['u_type'] = 'user';
            setcookie('u_id',   $oUser->getID(),     $nExpire, '/', '.'.__ENV_DMN); $_COOKIE['u_id']   = $oUser->getID();
            setcookie('u_nick', $oUser->get('nick'), $nExpire, '/', '.'.__ENV_DMN); $_COOKIE['u_nick'] = $oUser->get('nick');
            /// 最后登录时间 ///
            $oUser->set('time_lastlogin', date('Y-m-d H:i:s'));
            $oUser->update();
            return true;
        }
        else {
            return false;
        }
    }

/// 缩略图相关 ///
    function calcThumbUrl($nID, $sFile) {
		if (!(0 < $nID)) { $nID = $this->getID(); }
        if (!(0 < $nID)) { return false; }
        if (!$sFile) { return false; }
        $sNumber = str_pad($nID, 9, '0', STR_PAD_LEFT);
		$sDir = "/".substr($sNumber, 0, 3)."/".substr($sNumber, 3, 3)."/".substr($sNumber, 6, 3)."/";
		return "/user{$sDir}{$sFile}";
    }
    function saveThumb($sSrcPath) {
		ini_set('memory_limit', '512M'); // 为了图片处理，临时放开内存限制。
        /// 得到图片信息 ///
        list($nOldW, $nOldH, $nType) = getimagesize($sSrcPath);
        if (IMAGETYPE_GIF == $nType) {
			$hOld = imagecreatefromgif($sSrcPath);
			$sExt = 'gif';
        }
        elseif (IMAGETYPE_JPEG == $nType) {
            $hOld = imagecreatefromjpeg($sSrcPath);
			$sExt = 'jpg';
        }
        elseif (IMAGETYPE_PNG == $nType) {
            $hOld = imagecreatefrompng($sSrcPath);
			$sExt = 'png';
        }
		else { return false; } // 只支持gif/jpg/png
		/// 保存源文件 ///
		if (!($sUrl = $this->calcThumbUrl(null, "source.{$sExt}"))) { return false; }
		mkdir_plus(dirname(__PHY_STO.$sUrl)); // 生成目录
		move_uploaded_file($sSrcPath, __PHY_STO.$sUrl); // 保存
		$sSrcPath = __PHY_STO.$sUrl;
		/// 生成图片 ///
		$rTypes = array(
			'156x156.jpg',
			'220x220.jpg',
		);
		$cnt = 0;
		foreach ($rTypes as $sFile) {
			if (!($sUrl = $this->calcThumbUrl(null, $sFile))) { continue; }
			mkdir_plus(dirname(__PHY_STO.$sUrl)); // 生成目录
			preg_match('/^(\d+)x(\d+)\.(\w+)$/', $sFile, $r);
			list($x, $nNewW, $nNewH, $sExt) = $r;
			$hNew = imagecreatetruecolor($nNewW, $nNewH);
			$cWhite = imagecolorallocate($hNew, 255, 255, 255);
			imagefilledrectangle($hNew, 0, 0, $nNewW, $nNewH, $cWhite); // 画一个白底
			list($fRangeW, $fRangeH) = scale_rectangle(array($nNewW, $nNewH), array($nOldW, $nOldH), 'IN', 'EQUAL'); // 从原始图中算的copy范围
			imagecopyresampled($hNew, $hOld,
				0, 0, round(($nOldW - $fRangeW)/2), round(($nOldH - $fRangeH)/2),
				$nNewW, $nNewH, round($fRangeW), round($fRangeH));
			imagejpeg($hNew, __PHY_STO.$sUrl); // 保存
			imagedestroy($hNew);
			$cnt++;
		}
		imagedestroy($hOld);
		/// 标记已有图片 ///
		if ($cnt == sizeof($rTypes)) {
        	$this->set('thumb', 1);
			return true;
		}
		else { return false; }
	}
} /// end class uUser.


class uUserList extends ItemList {
    /// definition and constructor ///
    function uUserList($tablename=null) {
        ItemList::ItemList();
        $this->cfgClass("uUser");
        $this->cfgKeyField("id");
        $this->cfgAllField("id,email,nick,pswd,time_added,time_lastlogin,thumb,sign,sign_en,gender,demo,description,description_en,role_artist");
        $this->cfgTable(null == $tablename ? "unit_user" : $tablename);
    }

} /// end class uUserList.


/// related functions ///
function uUser_thumb($bHasThumb, $nID, $sFile) {
	if ($bHasThumb) {
		$sUrl = uUser::calcThumbUrl($nID, $sFile);
	}
	else { $sUrl = "/user/default/{$sFile}"; }
	return __DIR_STO.$sUrl;
}
function uUser_i18n($nID, $sField) {
	static $rCache = array();
	if (!isset($rCache['LangFields'])) {
		$rCache['LangFields'] = '|sign|description';
	}
	if (!isset($rCache[$nID])) {
		$oOne = new uUser($nID);
		$rCache[$nID] = $oOne->getData();
	}
	if ('en' == $_SESSION['LANG'] && strpos($rCache['LangFields'], $sField)) {
		$sField .= '_en';
		return $rCache[$nID][$sField];
	}
	else { return $rCache[$nID][$sField]; }
}

?>
